package com.kly.smartbi.controller.bi;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.kly.smartbi.annotation.AuthCheck;
import com.kly.smartbi.common.BaseResponse;
import com.kly.smartbi.common.DeleteRequest;
import com.kly.smartbi.common.ErrorCode;
import com.kly.smartbi.common.ResultUtils;
import com.kly.smartbi.constant.UserConstant;
import com.kly.smartbi.exception.BusinessException;
import com.kly.smartbi.exception.ThrowUtils;
import com.kly.smartbi.model.dto.post.PostAddRequest;
import com.kly.smartbi.model.dto.post.PostEditRequest;
import com.kly.smartbi.model.dto.post.PostQueryRequest;
import com.kly.smartbi.model.dto.post.PostUpdateRequest;
import com.kly.smartbi.model.entity.Post;
import com.kly.smartbi.model.entity.User;
import com.kly.smartbi.model.vo.PostVO;
import com.kly.smartbi.service.PostService;
import com.kly.smartbi.service.PostThumbService;
import com.kly.smartbi.service.UserService;
import com.kly.smartbi.utils.BloomFilterUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.kly.smartbi.constant.PostRedisConstant.*;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/post")
@Slf4j
public class PostController {

    @Resource
    private PostService postService;

    @Resource
    private UserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private PostThumbService postThumbService;

    @Resource
    private BloomFilterUtil bloomFilterUtil;

    @Resource
    private RedissonClient redissonClient;

    private RBloomFilter<String> bloomFilter;

    Cache<String, String> LOCAL_CACHE = Caffeine.newBuilder()
            .maximumSize(10_000)
            .initialCapacity(1024)
            .expireAfterWrite(Duration.ofMinutes(TEN_TIME_TTL + RandomUtil.randomInt(1, 5)))
            .build();

    @PostConstruct
    public void init() {
        // 在Spring Bean初始化完成后创建布隆过滤器
        this.bloomFilter = bloomFilterUtil
                .create(POST_GET_BLOOM_NAME, 1000000, 0.001);
    }

    // region 增删改查

    /**
     * 创建
     *
     * @param postAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<String> addPost(@RequestBody PostAddRequest postAddRequest, HttpServletRequest request) {
        if (postAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = new Post();
        BeanUtils.copyProperties(postAddRequest, post);
        List<String> tags = postAddRequest.getTags();
        if (tags != null) {
            post.setTags(JSONUtil.toJsonStr(tags));
        }
        postService.validPost(post, true);
        User loginUser = userService.getLoginUser(request);
        post.setUserId(loginUser.getId());
        post.setFavourNum(0);
        post.setThumbNum(0);
        // 上传帖子
        boolean result = postService.save(post);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success("ok");
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePost(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Post oldPost = postService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPost.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = postService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param postUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePost(@RequestBody PostUpdateRequest postUpdateRequest) {
        if (postUpdateRequest == null || postUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = new Post();
        BeanUtils.copyProperties(postUpdateRequest, post);
        List<String> tags = postUpdateRequest.getTags();
        if (tags != null) {
            post.setTags(JSONUtil.toJsonStr(tags));
        }
        // 参数校验
        postService.validPost(post, false);
        long id = postUpdateRequest.getId();
        // 判断是否存在
        Post oldPost = postService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = postService.updateById(post);
        return ResultUtils.success(result);
    }


    /**
     * 添加bloomFilter参数
     */
    @PostMapping("/add/bloomFilter")
    public BaseResponse<String> addBloomFilter() {
        // 添加到布隆过滤器
        postService.lambdaQuery().list().forEach(post -> {
            bloomFilter.add(String.valueOf(post.getId()));
        });
        return ResultUtils.success("ok");
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    @AuthCheck(mustRole = UserConstant.DEFAULT_ROLE)
    public BaseResponse<PostVO> getPostVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 防止缓存雪崩 设置过期时间 随机值
        int expireTime = TEN_TIME_TTL + RandomUtil.randomInt(1, 5);
        // 判断是否为空 防止缓存穿透
        if (!bloomFilter.contains(String.valueOf(id))) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "帖子不存在");
        }
        // 多级缓存 caffeine redis 防止缓存雪崩
        String key = String.format("%s%s", POST_DETAIL_CACHE_KEY, id);
        String postCache = LOCAL_CACHE.getIfPresent(key);
        if (StrUtil.isNotBlank(postCache)) {
            return ResultUtils.success(JSONUtil.toBean(postCache, PostVO.class));
        }

        if ("".equals(postCache)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "帖子不存在");
        }

        // 查询缓存判断是否存在
        postCache = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(postCache)) {
            // 写入缓存 caffeine
            LOCAL_CACHE.put(key, postCache);
            return ResultUtils.success(JSONUtil.toBean(postCache, PostVO.class));
        }
        // 判断是否为空 防止缓存穿透
        if ("".equals(postCache)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "帖子不存在");
        }
        String lockKey = String.format("%s%s", POST_LOCK_DETAIL_KEY, id);
        RLock lock = redissonClient.getLock(lockKey);
        PostVO postVO = null;
        try {
            // 互斥锁 防止缓存击穿
            boolean tryLock = lock.tryLock(TEN_TIME_TTL, -1, TimeUnit.SECONDS);
            if (tryLock) {
                Post post = postService.getById(id);
                if (post == null) {
                    // 写入缓存 redis caffeine
                    LOCAL_CACHE.put(key, "");
                    stringRedisTemplate.opsForValue().set(key, "", expireTime, TimeUnit.MINUTES);
                    throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
                }
                postVO = postService.getPostVO(post, request);
                postThumbService.setHasThumbByZSet(postVO);
                // 写入缓存 redis caffeine
                stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(postVO), expireTime, TimeUnit.MINUTES);
                LOCAL_CACHE.put(key, JSONUtil.toJsonStr(postVO));
            }
        } catch (Exception e) {
            log.info("getPostById error");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统错误");
        } finally {
            // 判断是否持有锁 释放锁
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return ResultUtils.success(postVO);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param postQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Post>> listPostByPage(@RequestBody PostQueryRequest postQueryRequest) {
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        Page<Post> postPage = postService.page(new Page<>(current, size),
                postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postPage);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PostVO>> listPostVOByPage(@RequestBody PostQueryRequest postQueryRequest,
                                                       HttpServletRequest request) {
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();

        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = postService.page(new Page<>(current, size),
                postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postService.getPostVOPage(postPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<PostVO>> listMyPostVOByPage(@RequestBody PostQueryRequest postQueryRequest,
                                                         HttpServletRequest request) {
        if (postQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        postQueryRequest.setUserId(loginUser.getId());
        long current = postQueryRequest.getCurrent();
        long size = postQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = postService.page(new Page<>(current, size),
                postService.getQueryWrapper(postQueryRequest));
        return ResultUtils.success(postService.getPostVOPage(postPage, request));
    }

    // endregion

    /**
     * 分页搜索（从 ES 查询，封装类）
     *
     * @param postQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/search/page/vo")
    public BaseResponse<Page<PostVO>> searchPostVOByPage(@RequestBody PostQueryRequest postQueryRequest,
                                                         HttpServletRequest request) {
        long size = postQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Post> postPage = postService.searchFromEs(postQueryRequest);
        return ResultUtils.success(postService.getPostVOPage(postPage, request));
    }

    /**
     * 编辑（用户）
     *
     * @param postEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPost(@RequestBody PostEditRequest postEditRequest, HttpServletRequest request) {
        if (postEditRequest == null || postEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Post post = new Post();
        BeanUtils.copyProperties(postEditRequest, post);
        List<String> tags = postEditRequest.getTags();
        if (tags != null) {
            post.setTags(JSONUtil.toJsonStr(tags));
        }
        // 参数校验
        postService.validPost(post, false);
        User loginUser = userService.getLoginUser(request);
        long id = postEditRequest.getId();
        // 判断是否存在
        Post oldPost = postService.getById(id);
        ThrowUtils.throwIf(oldPost == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldPost.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = postService.updateById(post);
        return ResultUtils.success(result);
    }


    /**
     * 返回标签列表
     */
    @GetMapping("/list/tag")
    public BaseResponse<List<String>> listTagList() {
        List<String> tagList = new ArrayList<>();
        tagList.add("编程");
        tagList.add("算法");
        tagList.add("数据结构");
        tagList.add("生活");
        tagList.add("音乐");
        tagList.add("旅行");
        tagList.add("美食");
        tagList.add("电影");
        tagList.add("游戏");
        tagList.add("科技");
        tagList.add("体育");
        return ResultUtils.success(tagList);
    }
}
